import { createRouter, createWebHistory } from 'vue-router'
import login from '../views/login.vue'
import A1Main from '../views/A1/A1Main.vue'
import B from '../views/B/B.vue'

// A2、A3和A4组件采用懒加载方式
const A2Main = () => import('../views/A2/A2Main.vue')
const A3Main = () => import('../views/A3/A3Main.vue')
const A4Main = () => import('../views/A4/A4Main.vue')

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login,
    meta: { requiresAuth: false }
  },
  {
    path: '/a1',
    name: 'a1',
    component: A1Main,
    meta: { requiresAuth: true, roles: ['a1'] }
  },
  {
    path: '/b',
    name: 'b',
    component: B,
    meta: { requiresAuth: true, roles: ['b'] }
  },
  {
    path: '/a2',
    name: 'a2',
    component: A2Main,
    meta: { requiresAuth: true, roles: ['a2'] }
  },
  {
    path: '/a3',
    name: 'a3',
    component: A3Main,
    meta: { requiresAuth: true, roles: ['a3'] }
  },
  {
    path: '/a4',
    name: 'a4',
    component: A4Main,
    meta: { requiresAuth: true, roles: ['a4'] }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/B/re.vue')
  },
  {
    path: '/update-pass',
    name: 'UpdatePass',
    component: () => import('../views/UpdatePass.vue'),
    meta: { requiresAuth: true }
  },
  // 默认路由 - 重定向到登录页
  {
    path: '/',
    redirect: '/login'
  },
  // 捕获所有未匹配的路由，重定向到登录页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局变量，用于第一次加载标记
let isFirstLoad = true

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const userRole = localStorage.getItem('userRole')
  
  // 首次加载时直接重定向到登录页（如果未登录）
  if (isFirstLoad && !isLoggedIn && to.path !== '/login') {
    isFirstLoad = false
    return next({ path: '/login', replace: true })
  }
  
  // 设置首次加载标志为false
  isFirstLoad = false
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 未登录，重定向到登录页
    return next({ name: 'login', replace: true })
  } 
  // 检查用户角色是否有权限访问该页面
  else if (to.meta.requiresAuth && to.meta.roles && !to.meta.roles.includes(userRole)) {
    // 无权限，根据用户角色重定向到对应页面
    if (['a1', 'a2', 'a3', 'a4', 'b'].includes(userRole)) {
      return next({ name: userRole, replace: true })
    } else {
      // 未知角色，返回登录页
      return next({ name: 'login', replace: true })
    }
  }
  // 如果已登录且尝试访问登录页，重定向到对应角色的主页
  else if (to.name === 'login' && isLoggedIn) {
    if (['a1', 'a2', 'a3', 'a4'].includes(userRole)) {
      return next({ name: userRole, replace: true })
    } else {
      // 未知角色，留在登录页重新登录
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('userRole')
      localStorage.removeItem('username')
      localStorage.removeItem('token')
      return next()
    }
  }
  else {
    // 其他情况正常放行
    next()
  }
})

export default router 